package com.admin.contorl;

import java.io.IOException;
import java.net.URL;
import java.util.Map;

import com.admin.common.AlertUtils;
import com.admin.common.FileUtils;
import com.admin.common.Show;
import com.admin.entity.adminList;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

public class IndexViewControl {
    @FXML
    private Button btn_login;
    @FXML
    private Button btn_register;
    @FXML
    private TextField txt_id;
    @FXML
    private PasswordField txt_password;

    public void login() {
        try {
            String id = txt_id.getText();
            String password = txt_password.getText();
            if (id.isEmpty() || password.isEmpty()) {
                AlertUtils.showDialog("提示", "请输入完整信息");
                return;
            } else {
                Map<String, adminList> adminMap = FileUtils
                        .readObject("com\\admin\\admin.txt");
                if (!adminMap.containsKey(id)) {
                    AlertUtils.showDialog("提示", "管理员不存在");
                    return;
                }
                if (!adminMap.get(id).getPassword().equals(password)) {
                    AlertUtils.showDialog("提示", "密码错误");
                    return;
                }
                FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/admin/view/adminView.fxml"));
                adminViewControl adminViewController = new adminViewControl(
                        "系统管理员： " + adminMap.get(id).getUserName());
                loader.setController(adminViewController);
                Stage stage = (Stage) btn_login.getScene().getWindow();
                Parent root = loader.load();
                Scene scene = new Scene(root);
                stage.setScene(scene);
                // AlertUtils.showDialog("提示", "登录成功")
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void register() {
        try {
            Stage stage = (Stage) btn_login.getScene().getWindow();
            URL url = getClass().getResource("/com/admin/view/RegisterView.fxml");
            Show.show(stage, url, "注册页面");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}